﻿#include "TrQuoteData.h"

TrQuoteData::TrQuoteData(QObject *parent) : QObject(parent)
{
    m_pManager = new QNetworkAccessManager(this);
    if (QSslSocket::supportsSsl() == false)
    {
        qDebug()<<"QSslSocket = "<<QSslSocket::sslLibraryBuildVersionString();
        qDebug() << "OpenSSL:" << QSslSocket::supportsSsl();
    }
}

QNetworkRequest TrQuoteData::Request()
{
    QNetworkRequest request;
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);
    return request;
}

void TrQuoteData::quote(const QString& code, int period)
{
    QString url = period == 0 ? SINA_D : SINA_M;
    url.replace("{:1}", code);
    period == 0 ? url.replace("{:2}", QDate::currentDate().toString("yyyy_MM_dd")) : url.replace("{:2}", QString::number(period));

    QNetworkRequest request = this->Request();
    request.setUrl(QUrl(url));

    QNetworkReply *pReply = m_pManager->get(request);
    connect(pReply, SIGNAL(finished()), this, SLOT(Finished()));
    connect(pReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
}

void TrQuoteData::Finished()
{
    QNetworkReply *pReply = (QNetworkReply*)sender();
    QString codeContent = pReply->readAll();
    this->handleData(codeContent);
}

void TrQuoteData::onError(QNetworkReply::NetworkError e)
{
    qDebug() << __FUNCTION__ << e;
}

void TrQuoteData::handleData(QString json)
{
    int length = json.length();
    int rig = length - 51;
    int lef = rig - 2;
    json = json.right(rig).left(lef);

    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(json.toLatin1(), &json_error);

    if (doc.isNull() || json_error.error != QJsonParseError::NoError)
    {
        qDebug() << json_error.errorString();
        return;
    }

    if (doc.isArray())
    {
        QJsonArray arr = doc.array();
        emit OnReplay(arr);
    }
}
